<template>
  <div class="tenantMenu_main main_container">
    <div class="main_header">
      <div class="padding_container">
        <div class="left"><Breadcrumb /></div>
        <div class="right">
          <HeaderOperation :parent="this" />
        </div>
      </div>
    </div>
    <div v-loading="loading" class="main_main">
      <SearchBar :parent="this" />
      <div ref="table_container" class="table_container">
        <el-table
          ref="table"
          :data="tableData"
          stripe
          border
          :height="tableHeight"
          row-key="id"
          :span-method="handleSpanMethod"
          :cell-class-name="cellClassName"
          :tree-props="{children: 'details', hasChildren: 'hasChildren'}"
          @sort-change="(column)=>{sortChange(column, this)}"
          @selection-change="(val)=>{selectionChange(val, this)}"
        >
          <el-table-column type="selection" align="center" width="70" />
          <Column
            v-for="(column,index) in tableColumns"
            :key="index"
            :prop="column.prop"
            :is-show="column.isShow"
            :label="column.label"
            :sortable="column.sortable"
            :width="column.width"
            :min-width="column.minWidth"
            :fixed="column.fixed"
            :align="column.align"
          />
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <pagination
        :total="total"
        :page.sync="pageData.pageNum"
        :limit.sync="pageData.pageSize"
        :selected-num="selectionsAll.length"
        @pagination="getList"
      />
    </div>

  </div>
</template>

<script>
import { productionProgressList as list, listForExport } from '@/api/ProductionManagement/progressTracking.js'
import { getDictSelects } from '@/api/common/common'
import { getBlob } from '@/utils/util'

export default {
  name: 'Index',
  data() {
    return {
      loading: false,
      pageId: '生产进度跟踪表', // 页面唯一标识
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'planCode',
        isAsc: 'desc'
      },
      total: 1, // 数据一共有多少条
      mainId: 'id', // 表格行ID
      tableHeight: '0', // 表格高度
      tableData: [], // 导出表格数据
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      defaultTableColumns: [// 表格常规字段（初始值）
        { prop: 'planCode', label: '生产计划单', minWidth: '160', isRegular: true },
        { prop: 'saleOrderCode', label: '销售订单', minWidth: '160', isRegular: true, canOrder: false },
        { prop: 'planTime', label: '计划日期', minWidth: '140', isRegular: true },
        { prop: 'materialCode', label: '物料编码', minWidth: '160', canOrder: false },
        { prop: 'materialName', label: '物料名称', minWidth: '120', canOrder: false },
        { prop: 'planNumber', label: '计划数量', align: 'right', minWidth: '100', canOrder: false },
        { prop: 'taskCode', label: '生产任务单号', minWidth: '140', canOrder: false },
        { prop: 'engineeringProcessName', label: '工序', minWidth: '120', canOrder: false },
        { prop: 'productNumber', label: '生产数量', align: 'right', minWidth: '100', canOrder: false },
        { prop: 'reportTotalNumber', label: '报工数量', align: 'right', minWidth: '100', canOrder: false },
        { prop: 'qualifiedTotalNumber', label: '合格数量', align: 'right', minWidth: '100', canOrder: false },
        { prop: 'percentage', label: '进度', align: 'right', minWidth: '100', canOrder: false },
        { prop: 'inWmsNum', label: '入库数量', align: 'right', minWidth: '100', canOrder: false },
        { prop: 'deliverNumber', label: '出库数量', align: 'right', minWidth: '100', canOrder: false },
        { prop: 'stockNum', label: '库存数量', align: 'right', minWidth: '100', canOrder: false }
      ],
      exportTableColumns: [// 表格导出字段（初始值）
        { prop: 'planCode', label: '生产计划单', minWidth: '160', isRegular: true },
        { prop: 'saleOrderCode', label: '销售订单', minWidth: '160', isRegular: true, canOrder: false },
        { prop: 'planTime', label: '计划日期', minWidth: '140', isRegular: true },
        { prop: 'materialCode', label: '物料编码', minWidth: '160', canOrder: false },
        { prop: 'materialName', label: '物料名称', minWidth: '120', canOrder: false },
        { prop: 'planNumber', label: '计划数量', align: 'right', minWidth: '100', canOrder: false },
        { prop: 'taskCode', label: '生产任务单号', minWidth: '140', canOrder: false },
        { prop: 'engineeringProcessName', label: '工序', minWidth: '120', canOrder: false },
        { prop: 'productNumber', label: '生产数量', align: 'right', minWidth: '100', canOrder: false },
        { prop: 'reportTotalNumber', label: '报工数量', align: 'right', minWidth: '100', canOrder: false },
        { prop: 'qualifiedTotalNumber', label: '合格数量', align: 'right', minWidth: '100', canOrder: false },
        { prop: 'percentage', label: '进度', align: 'right', minWidth: '100', canOrder: false },
        { prop: 'inWmsNum', label: '入库数量', align: 'right', minWidth: '100', canOrder: false },
        { prop: 'deliverNumber', label: '出库数量', align: 'right', minWidth: '100', canOrder: false },
        { prop: 'stockNum', label: '库存数量', align: 'right', minWidth: '100', canOrder: false }
      ],
      defaultSearchColumns: [// 搜索区常规字段（初始值）
        { prop: 'planCode', label: '生产计划单', type: 'input' },
        { prop: 'saleOrderCode', label: '销售订单', type: 'input' },
        { prop: 'planTime', label: '计划日期', type: 'time' },
        { prop: 'materialCode', label: '物料编码', type: 'input' },
        { prop: 'materialName', label: '物料名称', type: 'input' },
        { prop: 'taskCode', label: '生产任务单号', type: 'input' },
        { prop: 'engineeringProcessName', label: '工序', type: 'input' }
      ],
      operationData: [ // 右上角的操作按钮
        { label: '批量导出3', perm: '' },
        { label: '页面配置2', perm: '' }
      ],
      Updata: []
    }
  },
  watch: {
    tableData() {
      this.$nextTick(() => {
        for (const elementNodeListOfElement of document.querySelectorAll('.SaleOrderCodeColumnClass')) {
          if (!elementNodeListOfElement.childNodes[0].childNodes[0].className || elementNodeListOfElement.childNodes[0].childNodes[0].className == 'commonTableColumn') {
            const paddingNode = document.createElement('div')
            paddingNode.className = 'SaleOrderCodeColumnClass_expand'
            paddingNode.innerHTML = ''
            elementNodeListOfElement.childNodes[0].insertBefore(paddingNode, elementNodeListOfElement.childNodes[0].childNodes[0])
          }
        }
      })
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 1) {
        return 'SaleOrderCodeColumnClass'
      }
      if (!row.isNotselected) {
        return 'displayNoneClass'
      }
    },
    handleSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (column.property == 'materialCode' || column.property == 'materialName' || column.property == 'planNumber') {
        return row.materialId_span
      }
    },
    getList() {
      list(this.pageData).then(res => {
        res.data.forEach((item) => {
          item.isNotselected = true

          // 判断是否要合并行
          if (item.details && item.details.length > 1) {
            item.details.forEach((item2, index2) => {
              // 如果 materialId 是第一次出现，或者是第一条
              if (index2 == 0 || item.details[index2 - 1].materialId != item2.materialId) {
                // 查询这个 materialId 出现的次数
                const _rowspan = countFieldValue(item.details, 'materialId', item2.materialId)[item2.materialId]
                if (item.planCode == 'SCJH_000009') {
                  console.log('item2.materialId', item2.materialId)
                  console.log('_rowspan', _rowspan)
                  console.log('-----------------------')
                }
                const _colspan = _rowspan > 0 ? 1 : 0
                item2['materialId_span'] = [_rowspan, _colspan]
              } else {
                // 如果不是第一条,并且上一条的 materialId 和本次的 materialId 一样 , 那么本次这一条是要合并掉的
                if (index2 > 0 && item.details[index2 - 1].materialId == item2.materialId) {
                  item2['materialId_span'] = [0, 0]
                }
              }
            })
          }
        })
        this.tableData = res.data
        console.log('this.tableData', this.tableData)
        this.total = res.total
        // this.Updata = res.data
        this.loading = false
        this.$nextTick(() => {
          this.setSelectRow(this)// 设置行选中
          this.tableHeight = this.$refs.table_container.offsetHeight
          // this.$refs.table.doLayout()
        })
      })
    },
    getExportData(data) {
      return new Promise(function(resolve, reject) {
        listForExport(data).then(res => {
          resolve({ data: res.data })
        })
      })
    },
    // 合计行
    getSummaries(param) {
      const {
        columns
      } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index == 0) {
          sums[index] = '合计'
          return
        }
        switch (column.property) {
          case 'planNumber':
            sums[index] = this.Updata.planNumberSum
            break
        }
        switch (column.property) {
          case 'stockUpNumber':
            sums[index] = this.Updata.stockNumberSum
            break
        }
        switch (column.property) {
          case 'orderNumber':
            sums[index] = this.Updata.orderNumberSum
            break
        }
        switch (column.property) {
          case 'workTimeSum':
            sums[index] = this.Updata.workTimeSum
            break
        }
      })
      return sums
    }
  }
}

function countFieldValue(arr, field, value) {
  return arr.reduce((acc, curr) => {
    if (curr[field] === value) {
      acc[value] = (acc[value] || 0) + 1
    }
    return acc
  }, {})
}
</script>

<style lang="less" scoped>
/deep/.el-table .displayNoneClass .cell .el-checkbox__inner{
  display: none
}
/deep/ .SaleOrderCodeColumnClass{
  .cell{
    display: flex;
    width: 20px;
    line-height: 20px;
    height: 20px;
    text-align: center;
    margin-right: 3px;
  }
}
/deep/ .SaleOrderCodeColumnClass_expand{
    display: flex;
    width: 20px;
    line-height: 20px;
    height: 20px;
    text-align: center;
    margin-right: 3px;
}
</style>
